﻿using Furion.DatabaseAccessor;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Queer.Data.BaseEntity;
using Queer.Util;
using Queer.Util.Helper;
using System;
using System.Linq;
using System.Security.Claims;

namespace Queer.Data.DbContexts
{
    /// <summary>
    /// 默认数据库上下文
    /// </summary>
    [AppDbContext("DefaultConnectionString")]
    public class DefaultDbContext : AppDbContext<DefaultDbContext, MasterDbContextLocator>
    {
        /// <summary>
        /// 继承父类构造函数
        /// </summary>
        /// <param name="options"></param>
        public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
        {
            EnabledEntityChangedListener = true;
        }

        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
        {
            // 获取当前事件对应上下文
            var dbContext = eventData.Context;

            // 获取所有新增和更新的实体
            var entities = dbContext.ChangeTracker.Entries().Where(u => u.State == EntityState.Added || u.State == EntityState.Modified);

            var userId = (
                            NetHelper.HttpContext != null && NetHelper.HttpContext.User != null
                            ? NetHelper.HttpContext.User.FindFirstValue("UserId")
                            : string.Empty
                          )
                          .ParseToLong();

            foreach (var entity in entities)
            {
                var EnItems = entity.Properties;
                switch (entity.State)
                {
                    // 新增
                    case EntityState.Added:

                        entity.Property(nameof(DefaultEntity.Id)).CurrentValue = IdGeneratorHelper.Instance.GetId();
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.CreateTime)))
                        {
                            if (entity.Property(nameof(BusinessEntity.CreateTime)).CurrentValue.IsNullOrZero())
                            {
                                entity.Property(nameof(BusinessEntity.CreateTime)).CurrentValue = DateTime.Now;
                            }
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.CreateUserId)))
                        {
                            entity.Property(nameof(BusinessEntity.CreateUserId)).CurrentValue = userId;
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.IsDelete)))
                        {
                            entity.Property(nameof(BusinessEntity.IsDelete)).CurrentValue = false;
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.LastModifyTime)))
                        {
                            entity.Property(nameof(BusinessEntity.LastModifyTime)).CurrentValue = DateTime.Now;
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.LastModifyUserId)))
                        {
                            entity.Property(nameof(BusinessEntity.LastModifyUserId)).CurrentValue = userId;
                        }
                        break;
                    // 修改
                    case EntityState.Modified:
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.IsDelete)))
                        {
                            var IsDelete = (bool?)entity.Property(nameof(BusinessEntity.IsDelete)).CurrentValue;
                            if (IsDelete.GetValueOrDefault())
                            {
                                entity.Property(nameof(BusinessEntity.DeleteTime)).CurrentValue = DateTime.Now;
                                entity.Property(nameof(BusinessEntity.DeleteUserId)).CurrentValue = userId;
                            }
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.LastModifyTime)))
                        {
                            entity.Property(nameof(BusinessEntity.LastModifyTime)).CurrentValue = DateTime.Now;
                        }
                        if (EnItems.Any(p => p.Metadata.Name == nameof(BusinessEntity.LastModifyUserId)))
                        {
                            entity.Property(nameof(BusinessEntity.LastModifyUserId)).CurrentValue = userId;
                        }
                        break;
                }
            }
        }
    }
}